<template>
  <div class="assessment-container">
    <!-- 测评介绍 -->
    <div class="assessment-intro" v-if="!started && !finished">
      <h2>儿童心理健康AI测评</h2>
      <div class="intro-content">
        <p>本测评采用AI智能分析系统，根据您孩子的具体情况动态生成个性化问题。</p>
        <ul>
          <li>每次测评问题都是独特的，更贴合您孩子的实际情况</li>
          <li>AI会根据您的回答实时调整后续问题</li>
          <li>完成测评后，您将获得AI生成的专业分析报告</li>
        </ul>
      </div>
      <el-button type="primary" size="large" @click="startAssessment" :loading="loading">
        开始测评
      </el-button>
    </div>

    <!-- 测评问题 -->
    <div class="assessment-questions" v-if="started && !finished">
      <div class="progress-info">
        <div class="question-progress">
          问题 {{ currentQuestionIndex + 1 }}/{{ questions.length }}
        </div>
        <el-progress 
          :percentage="(currentQuestionIndex + 1) / questions.length * 100" 
          :format="() => ''" 
          :stroke-width="8"
        />
      </div>

      <div class="question-card" v-loading="questionLoading">
        <h3>{{ currentQuestion?.question }}</h3>
        <div class="options">
          <el-input
            v-model="currentAnswer"
            type="textarea"
            :rows="4"
            placeholder="请描述您的观察和想法..."
          />
        </div>
        <div class="question-actions">
          <el-button 
            v-if="currentQuestionIndex > 0" 
            @click="previousQuestion"
            :disabled="questionLoading"
          >上一题</el-button>
          <el-button 
            type="primary" 
            @click="nextQuestion" 
            :disabled="!currentAnswer || questionLoading"
          >
            {{ currentQuestionIndex === questions.length - 1 ? '完成' : '下一题' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 测评结果 -->
    <div class="assessment-result" v-if="finished">
      <div class="result-card" v-loading="analysisLoading">
        <div class="result-header">
          <el-icon class="result-icon"><Medal /></el-icon>
          <h2>AI分析报告</h2>
        </div>
        
        <div class="analysis-content">
          <h4>综合分析</h4>
          <div class="analysis-text" v-html="analysisResult.summary"></div>
          
          <h4>具体表现</h4>
          <div class="analysis-aspects">
            <div 
              v-for="(aspect, index) in analysisResult.aspects" 
              :key="index"
              class="aspect-item"
            >
              <h5>{{ aspect.title }}</h5>
              <p>{{ aspect.content }}</p>
            </div>
          </div>

          <h4>建议措施</h4>
          <ul class="suggestions-list">
            <li 
              v-for="(suggestion, index) in analysisResult.suggestions" 
              :key="index"
            >
              {{ suggestion }}
            </li>
          </ul>
        </div>

        <div class="result-actions">
          <el-button @click="restartAssessment">重新测评</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Medal } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { post, postWithLongTimeout } from '@/utils/request'

const loading = ref(false)
const questionLoading = ref(false)
const analysisLoading = ref(false)
const started = ref(false)
const finished = ref(false)
const currentQuestionIndex = ref(0)
const questions = ref([])
const answers = ref([])
const currentAnswer = ref('')
const analysisResult = ref({
  summary: '',
  aspects: [],
  suggestions: []
})

// 当前问题
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || null
})

// 生成问题
const handleGenerateQuestion = async (previousQA = []) => {
  try {
    questionLoading.value = true
    const res = await post('/api/assessment/generate-question', previousQA)
    console.log('收到的问题数据:', res)
    return res
  } catch (error) {
    console.error('生成问题失败:', error)
    ElMessage.error('生成问题失败，请重试')
    throw error
  } finally {
    questionLoading.value = false
  }
}

// 开始测评
const startAssessment = async () => {
  try {
    loading.value = true
    // 生成第一个问题
    const firstQuestion = await handleGenerateQuestion()
    console.log('第一个问题:', firstQuestion)
    questions.value = [firstQuestion]  // 直接使用返回的对象
    answers.value = []
    currentAnswer.value = ''
    started.value = true
    finished.value = false
    currentQuestionIndex.value = 0
  } catch (error) {
    ElMessage.error('启动测评失败，请重试')
  } finally {
    loading.value = false
  }
}

// 下一题
const nextQuestion = async () => {
  // 保存当前答案
  answers.value[currentQuestionIndex.value] = currentAnswer.value

  // 如果当前索引小于问题总数-1，说明后面还有已生成的问题
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    currentAnswer.value = answers.value[currentQuestionIndex.value] || ''
    return
  }

  // 如果已经到达最大问题数，生成分析报告
  if (currentQuestionIndex.value >= 9) {
    await handleGenerateAnalysis()
    return
  }

  // 生成新问题
  try {
    const qaRecords = questions.value.map((q, i) => ({
      question: q.question,
      answer: answers.value[i]
    }))
    console.log('发送的问答记录:', qaRecords)
    const nextQuestion = await handleGenerateQuestion(qaRecords)
    console.log('收到的下一个问题:', nextQuestion)
    questions.value.push(nextQuestion)
    currentQuestionIndex.value++
    currentAnswer.value = ''
  } catch (error) {
    // 错误已在generateQuestion中处理
    return
  }
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    currentAnswer.value = answers.value[currentQuestionIndex.value] || ''
  }
}

// 生成分析报告
const handleGenerateAnalysis = async () => {
  try {
    analysisLoading.value = true
    finished.value = true
    ElMessage.info('正在生成分析报告，这可能需要一点时间...')

    const qaRecords = questions.value.map((q, i) => ({
      question: q.question,
      answer: answers.value[i]
    }))

    const res = await post('/api/assessment/generate-analysis', qaRecords)
    analysisResult.value = res
    ElMessage.success('分析报告生成完成')
    
  } catch (error) {
    console.error('生成分析报告失败:', error)
    ElMessage.error('生成分析报告失败，请重试')
    finished.value = false
  } finally {
    analysisLoading.value = false
  }
}

// 重新测评
const restartAssessment = () => {
  started.value = false
  finished.value = false
  currentQuestionIndex.value = 0
  questions.value = []
  answers.value = []
  currentAnswer.value = ''
  analysisResult.value = {
    summary: '',
    aspects: [],
    suggestions: []
  }
}
</script>

<style scoped>
.assessment-container {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.assessment-intro {
  background: white;
  border-radius: 8px;
  padding: 32px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.intro-content {
  margin: 24px 0;
  text-align: left;
}

.intro-content ul {
  padding-left: 20px;
  margin: 16px 0;
}

.intro-content li {
  margin: 8px 0;
  color: #666;
}

.progress-info {
  margin-bottom: 24px;
}

.question-progress {
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.question-card {
  background: white;
  border-radius: 8px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.question-card h3 {
  margin: 0 0 24px;
  color: #303133;
}

.options {
  margin: 24px 0;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 32px;
}

.result-card {
  background: white;
  border-radius: 8px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.result-header {
  text-align: center;
  margin-bottom: 32px;
}

.result-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 16px;
}

.analysis-content {
  margin: 24px 0;
}

.analysis-content h4 {
  margin: 24px 0 16px;
  color: #303133;
  font-size: 18px;
}

.analysis-text {
  color: #666;
  line-height: 1.8;
}

.analysis-aspects {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin: 16px 0;
}

.aspect-item {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
}

.aspect-item h5 {
  margin: 0 0 8px;
  color: #303133;
}

.aspect-item p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.suggestions-list {
  list-style: none;
  padding: 0;
  margin: 16px 0;
}

.suggestions-list li {
  margin: 12px 0;
  padding-left: 24px;
  position: relative;
  color: #666;
  line-height: 1.6;
}

.suggestions-list li::before {
  content: "•";
  color: #409EFF;
  position: absolute;
  left: 8px;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
}
</style> 